/**
 * 现代化主题管理器
 * 提供完整的主题切换、响应式布局和用户体验优化
 */

class ModernThemeManager {
    constructor() {
        this.themes = {
            default: {
                name: '默认主题',
                colors: {
                    primary: '#0073aa',
                    secondary: '#f1f1f1',
                    accent: '#ff6b6b',
                    success: '#28a745',
                    warning: '#ffc107',
                    danger: '#dc3545',
                    info: '#17a2b8'
                }
            },
            dark: {
                name: '暗黑主题',
                colors: {
                    primary: '#0073aa',
                    secondary: '#1e1e1e',
                    accent: '#ff6b6b',
                    success: '#28a745',
                    warning: '#ffc107',
                    danger: '#dc3545',
                    info: '#17a2b8'
                }
            },
            colorful: {
                name: '彩色主题',
                colors: {
                    primary: '#ff6b6b',
                    secondary: '#ffeaa7',
                    accent: '#74b9ff',
                    success: '#00b894',
                    warning: '#fdcb6e',
                    danger: '#e17055',
                    info: '#6c5ce7'
                }
            },
            cyberpunk: {
                name: '赛博朋克',
                colors: {
                    primary: '#00ff88',
                    secondary: '#0a0a0a',
                    accent: '#ff0080',
                    success: '#00ff88',
                    warning: '#ffff00',
                    danger: '#ff0040',
                    info: '#00ffff'
                }
            },
            modern: {
                name: '现代简约',
                colors: {
                    primary: '#667eea',
                    secondary: '#f8fafc',
                    accent: '#764ba2',
                    success: '#10b981',
                    warning: '#f59e0b',
                    danger: '#ef4444',
                    info: '#3b82f6'
                }
            },
            nature: {
                name: '自然主题',
                colors: {
                    primary: '#059669',
                    secondary: '#f0fdf4',
                    accent: '#10b981',
                    success: '#22c55e',
                    warning: '#eab308',
                    danger: '#ef4444',
                    info: '#06b6d4'
                }
            }
        };
        
        this.currentTheme = 'default';
        this.isSystemDark = false;
        this.init();
    }
    
    init() {
        this.loadSavedTheme();
        this.detectSystemTheme();
        this.createThemeSwitcher();
        this.applyTheme(this.currentTheme);
        this.setupResponsiveHandlers();
        this.setupAnimations();
    }
    
    loadSavedTheme() {
        const saved = localStorage.getItem('spider-spa-theme');
        if (saved && this.themes[saved]) {
            this.currentTheme = saved;
        }
    }
    
    detectSystemTheme() {
        if (window.matchMedia) {
            const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
            this.isSystemDark = mediaQuery.matches;
            
            mediaQuery.addListener((e) => {
                this.isSystemDark = e.matches;
                if (this.currentTheme === 'auto') {
                    this.applyTheme('auto');
                }
            });
        }
    }
    
    createThemeSwitcher() {
        // 创建主题切换器容器
        const switcher = document.createElement('div');
        switcher.className = 'modern-theme-switcher';
        switcher.innerHTML = `
            <div class="theme-switcher-header">
                <h4>主题设置</h4>
                <button class="theme-toggle-btn" title="切换主题">
                    <span class="theme-icon">🎨</span>
                </button>
            </div>
            <div class="theme-options">
                ${Object.entries(this.themes).map(([key, theme]) => `
                    <button class="theme-option ${key === this.currentTheme ? 'active' : ''}" 
                            data-theme="${key}" 
                            title="${theme.name}">
                        <div class="theme-preview" style="background: linear-gradient(135deg, ${theme.colors.primary}, ${theme.colors.accent})"></div>
                        <span class="theme-name">${theme.name}</span>
                    </button>
                `).join('')}
            </div>
        `;
        
        // 添加到侧边栏
        const sidebar = document.querySelector('.spider-nav-sidebar');
        if (sidebar) {
            sidebar.appendChild(switcher);
        }
        
        // 绑定事件
        this.bindThemeEvents(switcher);
    }
    
    bindThemeEvents(switcher) {
        // 主题选项点击事件
        switcher.querySelectorAll('.theme-option').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const theme = e.currentTarget.dataset.theme;
                this.setTheme(theme);
            });
        });
        
        // 主题切换按钮
        const toggleBtn = switcher.querySelector('.theme-toggle-btn');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => {
                switcher.classList.toggle('expanded');
            });
        }
    }
    
    setTheme(themeKey) {
        if (!this.themes[themeKey]) return;
        
        this.currentTheme = themeKey;
        this.applyTheme(themeKey);
        this.saveTheme(themeKey);
        this.updateActiveTheme(themeKey);
    }
    
    applyTheme(themeKey) {
        const theme = this.themes[themeKey];
        if (!theme) return;
        
        const root = document.documentElement;
        
        // 移除所有主题类
        Object.keys(this.themes).forEach(key => {
            root.classList.remove(`${key}-theme`);
        });
        
        // 应用新主题
        if (themeKey !== 'default') {
            root.classList.add(`${themeKey}-theme`);
        }
        
        // 设置CSS变量
        Object.entries(theme.colors).forEach(([key, value]) => {
            root.style.setProperty(`--${key}-color`, value);
        });
        
        // 添加主题切换动画
        root.style.transition = 'all 0.5s cubic-bezier(0.4, 0, 0.2, 1)';
        setTimeout(() => {
            root.style.transition = '';
        }, 500);
        
        console.log(`主题已切换到: ${theme.name}`);
    }
    
    saveTheme(themeKey) {
        localStorage.setItem('spider-spa-theme', themeKey);
    }
    
    updateActiveTheme(themeKey) {
        document.querySelectorAll('.theme-option').forEach(btn => {
            btn.classList.toggle('active', btn.dataset.theme === themeKey);
        });
    }
    
    setupResponsiveHandlers() {
        // 窗口大小变化处理
        let resizeTimeout;
        window.addEventListener('resize', () => {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
                this.handleResponsiveLayout();
            }, 250);
        });
        
        // 初始检查
        this.handleResponsiveLayout();
    }
    
    handleResponsiveLayout() {
        const width = window.innerWidth;
        const sidebar = document.querySelector('.spider-nav-sidebar');
        const content = document.querySelector('.spider-content-area');
        
        if (!sidebar || !content) return;
        
        // 移动端处理
        if (width <= 768) {
            sidebar.classList.add('mobile-mode');
            content.classList.add('mobile-mode');
        } else {
            sidebar.classList.remove('mobile-mode');
            content.classList.remove('mobile-mode');
        }
        
        // 平板端处理
        if (width <= 992 && width > 768) {
            sidebar.classList.add('tablet-mode');
        } else {
            sidebar.classList.remove('tablet-mode');
        }
    }
    
    setupAnimations() {
        // 添加页面加载动画
        document.addEventListener('DOMContentLoaded', () => {
            document.body.classList.add('loaded');
        });
        
        // 添加滚动动画
        this.setupScrollAnimations();
    }
    
    setupScrollAnimations() {
        const observerOptions = {
            threshold: 0.1,
            rootMargin: '0px 0px -50px 0px'
        };
        
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    entry.target.classList.add('animate-in');
                }
            });
        }, observerOptions);
        
        // 观察所有卡片和面板
        document.querySelectorAll('.overview-card, .trend-left-panel, .trend-right-panel').forEach(el => {
            observer.observe(el);
        });
    }
    
    // 获取当前主题信息
    getCurrentTheme() {
        return {
            key: this.currentTheme,
            name: this.themes[this.currentTheme].name,
            colors: this.themes[this.currentTheme].colors
        };
    }
    
    // 动态添加新主题
    addTheme(key, theme) {
        this.themes[key] = theme;
        this.createThemeSwitcher();
    }
    
    // 移除主题
    removeTheme(key) {
        if (key === 'default') return;
        delete this.themes[key];
        if (this.currentTheme === key) {
            this.setTheme('default');
        }
    }
}

// 创建全局实例
window.ModernThemeManager = new ModernThemeManager();

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = ModernThemeManager;
}
